<template>
  <div class="add-close-adv-container">
    <!-- 表单头部 -->
    <div class="form-header">
      <h2 class="title">闭环医嘱信息</h2>
    </div>

    <!-- 主内容区域 -->
    <el-form 
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="220px"
      class="form-content"
      v-loading="loading"
    >
      <!-- 医嘱中文名称 -->
      <el-form-item 
        label="医嘱中文名称 :"
        prop="ADVICE_NAME"
        :error="checkErrors[0]"
      >
        <el-input
          v-model="formData.ADVICE_NAME"
          placeholder="请输入1-30个字符"
          :maxlength="30"
          clearable
          @blur="inputCheck(0)"
          @input="inputCheck(0)"
        />
      </el-form-item>

      <!-- 医嘱英文名称 -->
      <el-form-item 
        label="医嘱英文名称（视图名称） :"
        prop="viewName"
        :error="checkErrors[1]"
      >
        <div class="input-with-prefix">
          <el-input
            v-model="formData.VIEW_NAME"
            placeholder="请输入1-30个英文字符"
            :maxlength="30"
            clearable
            @blur="inputCheck(1)"
            @input="inputCheck(1)"
          />
        </div>
      </el-form-item>

      <!-- 多次执行记录 -->
      <el-form-item 
          label="一条医嘱是否可能包含多次执行记录 :"
          class="switch-item"
          prop="HAVE_MANY_TIMES"
        >
        <el-switch
          v-model="formData.HAVE_MANY_TIMES"
          :active-value="1"
          :inactive-value="0"
          active-color="#007077"
          inactive-color="#999999"
        />
      </el-form-item>

      <!-- 数据源 -->
      <el-form-item 
        label="数据源 :"
        prop="dataSourceId"
      >
        <el-select
          v-model="formData.dataSourceId"
          
          placeholder="指定数据源（可以为空）"
          class="select-input"
        >
          <el-option
            v-for="item in dataSourceList"
            :key="item.BASE_ID"
            :label="item.BASE_NAME"
            :value="item.BASE_ID"
          >
            <span :style="{ color: item.BASE_ID === -1 ? '#ff9900' : '#8492a6' }">
              {{ item.BASE_NAME }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
  <div class="field-config-container">
    <!-- 字段配置 -->
    <div class="section-header">
      <h3>字段配置 <span class="subtitle">（*代表固定字段）</span></h3>
    </div>
    <div class="field-config-list">
      <div v-for="(field, index) in configFields" :key="index" class="field-item">
        <div class="field-label">
          <span v-if="field.isRequired" class="required">*</span>
          {{ field.displayName }}（{{ field.fieldName }}）
        </div>
        <div class="equal-sign">等于</div>
        <el-input
          v-model="field.value"
          :placeholder="field.placeholder"
          @blur="validateField(field)"
          @input="validateField(field)"
          class="input-field"
          clearable
        />
        <div v-if="field.error" class="error-message">
          {{ field.errorMessage }}
        </div>
      </div>
    </div>

    <!-- Where条件 -->

    <!-- 按钮组 -->
    <div class="button-group">
      <el-button type="primary" @click="handleNextStep">保 存</el-button>
      <!-- <el-button type="primary" @click="handlePreviousStep">上 一 步</el-button> -->
      <el-button v-if="showErrorDialog" type="danger" @click="showErrorDetails">查看错误信息</el-button>
    </div>

    <!-- 错误提示对话框 -->
    <el-dialog title="错误提示" v-model="dialogVisible">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="错误信息" name="digerr">
          <pre class="error-details">{{ errorInfo }}</pre>
        </el-tab-pane>
        <el-tab-pane label="SQL信息" name="digsql">
          <pre class="error-details">{{ sqlInfo }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive ,onMounted,computed} from 'vue'
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus'
import { closeLoopDetailYz as useCloseLoopDetailYzStore,// 正确导入 Store 
  closeLoopDetailYzBase,
  closeLoopDetailYzColumn
 } from '@/stores/closeLoopList'; // 正确导入 Store

const showErrorDialog = ref(false); // 或其他初始值，根据你的业务逻辑
const route = useRoute(); // 获取路由参数
const loading = ref(false)
const formRef = ref()
const dialogVisible = ref(false);      // 新增：定义 dialogVisible
const errorInfo = ref('');             // 新增：错误信息
const sqlInfo = ref('');               // 新增：SQL 信息
const activeTab = ref('digerr');       // 新增：默认选中第一个标签

const closeLoopStore = useCloseLoopDetailYzStore(); // 获取 医嘱表信息Store 实例
const closeLoopBaseStore = closeLoopDetailYzBase(); // 获取 数据源Store 实例
const closeLoopColumnStore = closeLoopDetailYzColumn(); // 获取 字段配置Store 实例
// 表单数据
// 直接映射 Store 的 state 到表单
const formData = reactive({
  //医嘱配置下半部分
  ADVICE_ID: closeLoopColumnStore.closeLoopBaseColumnList.ADVICE_ID,
  COLUMN_NAME: closeLoopColumnStore.closeLoopBaseColumnList.COLUMN_NAME,
  COLUMN_SQL: closeLoopColumnStore.closeLoopBaseColumnList.COLUMN_SQL,
  ORDER_NUM: closeLoopColumnStore.closeLoopBaseColumnList.ORDER_NUM,
  COLUMN_COMMENT: closeLoopColumnStore.closeLoopBaseColumnList.COLUMN_COMMENT,

  HAVE_MANY_TIMES: 0, // 默认关闭
});
// 获取闭环ID
const closeLoopId = route.query.closeLoopId;//获取闭环ID
const dataSourceList  = computed(() => closeLoopBaseStore.closeLoopBaseList);

// 数据加载函数
const fetchData = async () => {
  if (closeLoopId) {
    loading.value = true;
    try {
      // 1. 获取闭环详情（主数据）
      await closeLoopStore.getCloseLoopDetailYz(closeLoopId); // 获取闭环详情
      // 更新表单数据（如果直接映射 Store 的 state，可能需要手动同步）
      Object.assign(formData, {
        ...closeLoopStore.closeLoopDetail,
        dataSourceId: closeLoopStore.closeLoopDetail.BASE_ID || '-1', // 显式赋值
        HAVE_MANY_TIMES: Number(closeLoopStore.closeLoopDetail.HAVE_MANY_TIMES)  || 0 // 确保默认值为0
      });
      // 强制触发更新
      // 2. 获取数据源列表
      await closeLoopBaseStore.fetchCloseLoopBaseList(); 
      // 3. 获取字段配置（下半部分）
      await closeLoopColumnStore.getCloseLoopBaseColumnList(closeLoopId); // 假设需要根据闭环ID获取字段配置
      // 初始化 configFields 的 value
      const columnList = closeLoopColumnStore.closeLoopBaseColumnList; // 获取字段配置列表
      // 验证数据格式
      if (!Array.isArray(columnList)) {
        throw new Error('字段配置数据格式错误');
      }
      
      // 初始化 configFields 的 value
      const columnMap = {};
      columnList.forEach(item => {
      const lowerColumnName = item.COLUMN_NAME.toLowerCase();
      columnMap[lowerColumnName] = item.COLUMN_SQL;
    });

    configFields.forEach(field => {
      field.value = columnMap[field.fieldName] || '';
    });

    // 按 ORDER_NUM 排序
    configFields.sort((a, b) => {
      const orderA = columnList.find(
        item => item.COLUMN_NAME === a.fieldName.toUpperCase()
      )?.ORDER_NUM || 0;
      const orderB = columnList.find(
        item => item.COLUMN_NAME === b.fieldName.toUpperCase()
      )?.ORDER_NUM || 0;
      return parseInt(orderA) - parseInt(orderB);
    });
    } catch (error) {
      console.error('获取闭环详情失败1:', error);
      ElMessage.error('获取数据失败，请重试');
    } finally {
      loading.value = false;
    }
  }
};
// 组件挂载时加载数据
onMounted(() => {
  fetchData();
});
// 字段配置数据
const configFields = reactive([
  {
    displayName: '医嘱/项目名',
    fieldName: 'order_name',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '医嘱/项目名 不能为空'
  },
  {
    displayName: '医嘱开立时间',
    fieldName: 'order_time',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '医嘱开立时间 不能为空'
  },
  {
    displayName: '开立医师',
    fieldName: 'order_doc',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '开立医师 不能为空'
  },
  {
    displayName: '医嘱号',
    fieldName: 'order_no',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '医嘱号 不能为空'
  },
  {
    displayName: '患者号',
    fieldName: 'pat_id',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '患者号 不能为空'
  },
  {
    displayName: '科室',
    fieldName: 'order_dept',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '科室 不能为空'
  },
  {
    displayName: '就诊流水号',
    fieldName: 'eid',
    isRequired: true,
    value: '',
    error: false,
    errorMessage: '就诊流水号 不能为空'
  },
  // 其他字段配置...
  {
    displayName: '额外展示字段',
    fieldName: 'show_info',
    isRequired: false,
    value: '',
    error: false,
    errorMessage: ''
  }
])

// 表单验证
// 字段验证方法
const validateField = (field) => {
  if (field.isRequired && !field.value) {
    field.error = true;
  } else {
    field.error = false;
  }
};
// 校验规则
const rules = {
  ADVICE_NAME: [
    { required: true, message: '医嘱中文名称不能为空', trigger: 'blur' }
  ],
  VIEW_NAME: [
    { required: true, message: '医嘱英文名称不能为空', trigger: 'blur' }
  ]
}
// 校验错误信息
const checkErrors = ref({
  0: '',
  1: '',
  2: '',
  10: '',
  11: '',
  12: ''
})
// 输入校验方法
const inputCheck = (index) => {
  // 根据索引执行对应的校验逻辑
  // 示例：
  if (index === 0 && !formData.ADVICE_NAME) {
    checkErrors.value[0] = '医嘱中文名称不能为空'
  } else {
    checkErrors.value[0] = ''
  }
  // 其他校验逻辑...
}
// 按钮事件
const handleNextStep = () => {
  // 验证所有必填字段
  configFields.forEach(field => {
    if (field.isRequired && !field.value) {
      field.error = true
    }
  })
  // 如果有错误，阻止下一步
  if (configFields.some(field => field.error)) {
    ElMessage.error('请填写所有必填字段')
    return
  }
}
</script>
<style scoped>
/* 主容器 */
.add-close-adv-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 表单头部 */
.form-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.title {
  font-size: 20px;
  color: #303133;
}

/* 表单样式 */
.form-content {
  width: 100%;
  max-width: 1200px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.input-with-prefix {
  display: flex;
  align-items: center;
}

.prefix,
.suffix {
  font-size: 14px;
  margin: 0 10px;
}

.dual-input-container {
  display: flex;
  gap: 15px;
}

.autocomplete,
.input-right {
  flex: 1;
}

.related-table-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.subtitle {
  color: #909399;
  margin-left: 10px;
}

.table-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.table-controls {
  margin-right: 15px;
}

.table-content {
  flex: 1;
  font-size: 14px;
  color: #606266;
}

.add-table-form {
  margin-top: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.form-group {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.select {
  flex: 1;
}

.on-condition {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.label {
  margin-right: 10px;
  color: #606266;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.save-btn {
  margin-top: 20px;
}
.field-config-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.subtitle {
  color: #909399;
  margin-left: 8px;
}

.field-config-list {
  margin-bottom: 30px;
}

.field-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.field-label {
  min-width: 220px;
  font-weight: 500;
  margin-right: 15px;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

.equal-sign {
  margin: 0 15px;
  color: #606266;
}

.input-field {
  flex: 1;
  margin-right: 15px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 240px;
}

.textarea-field {
  width: 100%;
  margin-bottom: 30px;
}

.button-group {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.error-details {
  white-space: pre-wrap;
  margin: 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>